package com.tanhua.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.commons.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Value("${gateway.excludedUrls}")
    private List<String> excludedUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取当前的请求路径
        String uri = exchange.getRequest().getURI().getPath();
        System.out.println(uri);

        //2 判断当前的请求路径是否需要进行鉴权，如果不需要鉴权，就放行
        if (excludedUrls.contains(uri)) {
            return chain.filter(exchange);
        }

        //3 从请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        // 清理token里面的 Bearer 值
        token = token.replace("Bearer ", "");

        //4 使用工具类进行校验
        boolean verifyToken = JwtUtils.verifyToken(token);

        //5 判断校验结果是否成功
        if (!verifyToken) {
            //如果不成功，就直接返回401
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode", 401);
            responseData.put("errMessage", "用户登录错误，需要重新登录。");

            return responseError(exchange.getResponse(), responseData);
        }

        //6 校验成功，放行
        return chain.filter(exchange);
    }

    //响应错误数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    //设置过滤器执行的优先级
    @Override
    public int getOrder() {
        //返回的结果越小,过滤器的优先级 越高
        //返回的结果越大,过滤器的优先级 越低
        return Ordered.LOWEST_PRECEDENCE;
    }
}
